package com.tqyan.dal.sharding;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;

public class HashShardingTableAlgorithm implements PreciseShardingAlgorithm<String> {

    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<String> shardingValue) {
        Object value = shardingValue.getValue();
        long index = HashAlgorithmUtil.hash(value + "", availableTargetNames.size());
        String tableName = shardingValue.getLogicTableName() + "_" + index;
        if (availableTargetNames.contains(tableName)) {
            return tableName;
        }
        throw new UnsupportedOperationException(String.format(
                "table: %s, shardingValue: %s, size: %s, index: %s, 分表%s不存在"
                , shardingValue.getLogicTableName(), value, availableTargetNames.size()
                , index, tableName));
    }

    public static void main(String[] args) {
        System.out.println(HashAlgorithmUtil.hash("25242815777144832", 16));
    }

}


